/*
 * acooly.cn Inc.
 * Copyright (c) 2016 All Rights Reserved.
 * create by zhangpu 
 * date:2016年5月1日
 *
 */
package com.acooly.module.openapi.client.provider.sinapay.utils;

import com.acooly.core.utils.Money;
import com.acooly.core.utils.conversion.AbstractTypeConverter;
import com.acooly.core.utils.conversion.StringTypeConverter;
import com.acooly.core.utils.conversion.TypeConversionException;

import java.util.Arrays;
import java.util.List;

/**
 * @author zhangpu
 */
public class MoneyTypeConverter extends AbstractTypeConverter<Money> {

	public Class<Money> getTargetType() {
		return Money.class;
	}

	public List<Class<?>> getSupportedSourceTypes() {
		return Arrays.asList(CharSequence.class, String[].class, Money.class);
	}

	public Money convert(Object value, Class<? extends Money> toType) {
		try {
			return dateValue(value, toType);
		} catch (TypeConversionException e) {
			throw e;
		} catch (Exception e) {
			throw new TypeConversionException(e);
		}
	}

	public static Money dateValue(Object value, Class<? extends Money> toType) {
		Money result = null;
		if (value != null && value.getClass().isArray()
				&& String.class.isAssignableFrom(value.getClass().getComponentType())) {
			value = StringTypeConverter.stringValue(value);
		}
		if (value != null && value instanceof String && ((String) value).length() > 0) {
			String sa = (String) value;
			result = Money.amout(sa);
		} else if (Money.class.isInstance(value)) {
			result = (Money) value;
		}
		return result;
	}
}
